# -*- coding: UTF-8 -*-
# @Time : 2021/12/9 0009 15:32
# @Author : lyw
# @Remark : 精密空调 db
import json
import logging
import re

from mxsoftpy.exception import DBError

from db.public.IOTManager.iot_base import IOTBaseDB
from index import _, mini_cache


class ACSelectDB(IOTBaseDB):
    device_type = "AirConditioning"
    query_field = ["mxlabel", "mxdevicetype", "mxparent"]

    def read_template(self):
        """
        读取设备模板
        @return:
        """
        db_path = "EntityTemplate"
        ups_temp_dict = {}
        ups_temp_cache = mini_cache.get("AIR_CONDITIONER_TEMP_CACHE")
        if ups_temp_cache:
            logging.info("空调模板读取缓存")

            return mini_cache["AIR_CONDITIONER_TEMP_CACHE"]
        for monitor_sub_code in self.tree.open(db_path, "IOT\\AirConditioning", file="base").sub_keys():
            sub_path = "\\".join(["IOT", "AirConditioning", monitor_sub_code, "MonitorEx"])
            plugin_dict = {"home_state": [], "param_info": [], "parts_info": [], "alert_info": []}
            print(sub_path)
            for monitor_key in self.tree.open(db_path, sub_path, file="base").sub_keys():
                monitor_value = self.tree.open(db_path, "\\".join([sub_path, monitor_key]), file="base").items()
                # 判断 是那一类字符
                monitor = self.regular_monitor(monitor_value["mxlabel"])
                # 增加到字典中
                self.query_temp(monitor_value["mxpluginname"], plugin_dict, monitor)
            else:
                if plugin_dict:
                    ups_temp_dict[monitor_sub_code] = plugin_dict
        mini_cache.set("AIR_CONDITIONER_TEMP_CACHE", ups_temp_dict, 24 * 60 * 60)
        logging.info("空调模板设置了缓存")
        return ups_temp_dict

    @staticmethod
    def regular_monitor(value):
        """
        匹配 字符
        @param value:
        @return:
        """

        if re.search("^回风温度$|^设定温度$|^回风湿度$|^设定湿度$|除湿状态|加湿状态", value):
            return "home_state"
        elif re.search("^运行状态$", value):
            return "param_info"
        elif re.search("压缩机|加热器|除湿状态|开关|加湿状态|风机状态|蒸发|冷凝器",
                       value) and not re.search("故障|告警|过载", value):
            return "parts_info"
        else:
            return "alert_info"

    def query_temp(self, mxpluginname, plugin_list: dict, monitor):
        """
        获取 plugin 数据
        @param monitor:
        @param mxpluginname:
        @param plugin_list:
        @return:
        """
        if isinstance(plugin_list.get(monitor), list):
            monitor_list = plugin_list[monitor]
        else:
            monitor_list = plugin_list[monitor] = []
        path = "PluginData"
        try:
            for i in self.tree.open(path, mxpluginname + "\\Output", file="base").sub_keys():
                plugin_data = self.tree.open(path, mxpluginname + "\\Output\\%s" % i, file="base").items(
                    ["mxlabel", "mxunit"])
                plugin_data["key"] = i
                plugin_data["plugin"] = mxpluginname
                if monitor == "alert_info":
                    monitor_key = self.regular_monitor(plugin_data["mxlabel"])
                    if monitor_key != monitor:
                        self.add_field(plugin_list, monitor_key, plugin_data)
                        continue
                plugin_data["name"] = self.tree.open(path, mxpluginname, file="base").fetchone_value("mxlabel")
                if monitor == "home_state":
                    self.add_field(plugin_list, "param_info", plugin_data)
                monitor_list.append(plugin_data)
        except DBError as e:
            logging.error(e)

    @staticmethod
    def add_field(plugin_list, monitor_key, plugin_data):
        """
        增加字段
        @param plugin_list:
        @param monitor_key:
        @param plugin_data:
        @return:
        """
        if isinstance(plugin_list.get(monitor_key), list):
            plugin_list[monitor_key].append(plugin_data)
        else:
            plugin_list[monitor_key] = [plugin_data]

    def get_sub_monitor(self, code, device_data):
        """
        获取设备的监测点信息
        @param dev_code:
        @return:
        """
        monitor_res_dict = {}
        try:
            ups_sub_list = self.tree.open("MXSE", "1\\1.SD\\%s\\%s.SubMonitor" % (code, code),
                                          file="ccubase").sub_keys()
            for ups_sub_key in ups_sub_list:
                ups_sub_monitor = self.tree.open("MXSE",
                                                 "1\\1.SD\\%s\\%s.SubMonitor\\%s" % (code, code, ups_sub_key),
                                                 file="ccubase").items(prop_list="mxpluginname")

                monitor_res_dict[ups_sub_key] = ups_sub_monitor["mxpluginname"]
        except DBError as e:
            logging.error(e)

        device_data["sub_monitor"] = monitor_res_dict

    def query_monitor_table_data(self, code, count=1):
        """
        查询记录
        @param count:
        @param code:
        @return:
        """
        try:
            monitor_table_list = self.table.open("MXSE", code).record_by_time(days=100, count=count)
            if monitor_table_list:
                return monitor_table_list[0]
        except DBError as e:
            logging.error(e)

    def param_middle(self, data_obj) -> dict:
        """
        基础查询 参数
        @param data_obj:
        @return:
        """
        return {"iot_code": data_obj.iot_code, "device_type": data_obj.device_type}

class ACListDB(ACSelectDB):
    def get_sub_monitor(self, code, device_data):
        pass


class ACRetrieveDB(ACSelectDB):
    pass


if __name__ == '__main__':
    print(json.dumps(ACSelectDB().read_template(), ensure_ascii=False))
